﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataSync.Common;
using log4net;
using System.Diagnostics;

namespace DataSync.Proc
{
    class TaskRunEngine
    {
        private static ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static ILog taskLog = LogManager.GetLogger("TaskLog");

        public TaskRunEngine()
        {
            //初始化任务信息
        }

        public void Run()
        {
            //读取配置
            var tasks = TaskConfig.GetTasks();
            Stopwatch st = new Stopwatch();
            foreach (var item in tasks)
            {
                var action = InterfaceFactory.GetTask(item);

                //检查任务状态
                var taskStatus = TaskRunControl.CheckTaskStatus(item.Id);
                if (taskStatus == 1)
                {
                    log.InfoFormat("任务【{0}】正在运行中,跳过本次处理", item.Name);
                    taskLog.InfoFormat("任务【{0}】正在运行中,跳过本次处理", item.Name);
                    continue;
                }

                //开始运行
                log.InfoFormat("任务【{0}】运行开始", item.Name);
                st.Reset();
                st.Start();
                try
                {
                    //更新运行状态
                    TaskRunControl.StartTaskRun(item.Id);

                    action.Init();
                    action.Run();
                }
                catch (Exception ex)
                {
                    log.Error(string.Format("任务【{0}】运行出错", item.Name), ex);
                    taskLog.ErrorFormat("任务【{0}】运行出错", item.Name);
                }
                finally
                {
                    //恢复状态
                    TaskRunControl.StopTaskRun(item.Id);
                }
                st.Stop();
                log.InfoFormat("任务【{0}】运行结束,本次花费:{1}秒", item.Name, st.ElapsedMilliseconds / 1000);
                taskLog.InfoFormat("任务【{0}】运行结束,本次花费:{1}秒", item.Name, st.ElapsedMilliseconds / 1000);
            }
        }
    }
}
